package com.leyou.item.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.mapper.CategoryBrandMapper;
import com.leyou.item.mapper.CategoryMapper;
import com.leyou.item.pojo.Brand;
import com.leyou.item.pojo.Category;
import com.leyou.pojo.PageResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @author 岩冰
 * @version 1.0
 * @date:2018/9/25
 */
@Service
public class BrandService {
    @Autowired
    private BrandMapper brandMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private CategoryBrandMapper categoryBrandMapper;
    public PageResult<Brand> queryPage(Integer page, Integer rows, String sortBy,Boolean desc, String key) {
        PageHelper.startPage(page, rows);
        Example example = new Example(Brand.class);
        if (StringUtils.isNotBlank(key)) {
            //添加条件
            example.createCriteria().andLike("name", "%" + key + "%")
                    .orEqualTo("letter", key);
        }
        if (StringUtils.isNotBlank(sortBy)) {
            example.setOrderByClause(sortBy+(desc ?" DESC":" ASC"));
        }
        Page<Brand> pageInfo = (Page<Brand>) brandMapper.selectByExample(example);
        return new PageResult<>(pageInfo.getTotal(), pageInfo);
    }
    @Transactional
    public void addBrand(Brand brand, Long[] cids) {
        brandMapper.insertSelective(brand);
        for (Long cid : cids) {
            brandMapper.insertCategoryBrand(cid,brand.getId());
        }
    }

    @Transactional
    public void editBrand(Brand brand, List<Long> cids) {
        brandMapper.updateByPrimaryKey(brand);
        //修改了商品分类的话先删除
        List<Category> categoryList = categoryMapper.queryByBrandId(brand.getId());
        //删除数据
        for (Category category : categoryList) {
            categoryBrandMapper.delete(category.getId(),brand.getId());
        }
        //添加数据
        for (Long cid : cids) {
            brandMapper.insertCategoryBrand(cid,brand.getId());
        }
    }

    @Transactional
    public void deleteBrandById(Long bid) {
        brandMapper.deleteByPrimaryKey(bid);
        categoryBrandMapper.deleteByBrandId(bid);
    }

    public Brand queryByBrandId(Long id) {
        return brandMapper.selectByPrimaryKey(id);
    }

    public List<Brand> queryBrandsByCid(Long cid) {

        return brandMapper.selectBrandsByCategoryId(cid);
    }

    public List<Brand> queryBrandByIds(List<Long> ids) {
        return  this.brandMapper.selectByIdList(ids);
    }
}
